const {Result} =require( "../util/result");

const express = require('express');
const router = express.Router();
const db = require('../util/db');
const {qPromise} = require("../util/qPromise");



/*todo GET tool listing. */
router.get('/', (req,res)=>{
    let sql='SELECT * FROM tools';
    db.query(sql,[],(data)=>{
        let result=new Result(200,'查询成功',data);
        res.json(result);
    })
});

/*todo-tools search page*/
router.get('/searchForAdmin',async (req,res)=>{
    let limit=10
    if(req.query.pageSize!=null)limit=req.query.pageSize
    let offset=0
    if(req.query.currentPage!=null)offset=(req.query.currentPage-1)*limit
    let sql=`select * from tools LIMIT ${limit} OFFSET ${offset};`
    let sql2=`select count(*) as total from tools`
    try {
        const [data, total] = await Promise.all([
            qPromise(sql,[]),
            qPromise(sql2, [])
        ]);
        res.json(new Result(200,'查询成功', {data: data, total: total[0].total}));
    } catch (error) {
        console.error(error);
        res.status(500).json(new Result(500,'查询失败', null));
    }
})

/*todo-tools add */
router.post('/addTool', (req, res) => {
    let sql = 'insert into tools(name,description,url,avatar) values(?,?,?,?)'

    db.query(sql, [req.body.name,req.body.description,req.body.url, req.body.avatar], (data) => {
        if (data.affectedRows === 1)
            res.json( new Result(200, '添加成功', null) )
        else res.json( new Result(500, '添加失败', null) )
    })
})
/*todo-tools update*/
router.put('/update', (req, res) => {
    let sql=`update tools set name=?,description=?,url=?,avatar=? where id=?`
    db.query(sql, [req.body.name,req.body.description,req.body.url,req.body.avatar,req.body.id], (data) => {
        if (data.affectedRows === 1)
            res.json( new Result(200, '修改成功', null))
        else res.json( new Result(500, '修改失败', null))
    })
})

/*todo-tools delete*/
router.delete('/delTool', (req, res) => {
    let sql = 'delete from tools where id=?'
    db.query(sql, [req.query.id], (data) =>{
        if (data.affectedRows === 1)
            res.json(new Result(200, '删除成功', null))
        else res.json(new Result(500, '删除失败', null))
    })
})


module.exports = router;
